package com.chaosj.webmagic.md;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ServiceLoaderUtil;
import com.chaosj.webmagic.DefaultLocalFileService;
import com.chaosj.webmagic.md.api.DefaultStorageModule;
import com.chaosj.webmagic.md.api.IStorageModule;
import com.google.common.base.Splitter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: StorageFacade
 * @description:
 * @author: caoyangjie
 * @date: 2021/12/30
 **/
public class StorageFacade {
    private static List<IStorageModule> storageModules = new ArrayList<>();
    private static IStorageModule defaultStorageModule = new DefaultStorageModule();

    public static List<IStorageModule> loadOrDefault(){
        return CollectionUtils.isEmpty(load()) ? Arrays.asList(defaultStorageModule) : load();
    }

    private static List<IStorageModule> load(){
        synchronized (storageModules){
            if( storageModules.isEmpty() ){
                synchronized (storageModules){
                    ServiceLoaderUtil.load(IStorageModule.class).forEach(ism->{
                        storageModules.add(ism);
                    });
                }
            }
        }
        return storageModules;
    }

    public static String storagePath(String topic){
//        return StrFormatter.format( "/software/源来如此/scrape-resources/{}", LocalDate.now().toString()) + (StringUtils.isEmpty(topic) ? "" : "/"+topic);
        return StrFormatter.format( "{}/{}", DefaultLocalFileService.basePath(), LocalDate.now().toString()) + (StringUtils.isEmpty(topic) ? "" : "/"+topic);
    }

    public static String analyzeTitle(String title){
        title = Splitter.on("-").splitToList(title).stream().collect(Collectors.joining(""));
        title = Splitter.on("_").splitToList(title).stream().collect(Collectors.joining(""));
        title = title.replaceAll("/","");
        return title;
    }

    public static List<String> analyze(String title){
        return Arrays.asList(title);
    }
}
